<?php

declare(strict_types=1);

namespace App\Controller;

use App\Model\ChatRoom;
use Hyperf\DbConnection\Db;
use Hyperf\Server\ServerFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Model\GroupRecord;
use App\Model\SecretRecord;
use App\Model\User;
use Hyperf\Di\Annotation\Inject;
use  App\Services\ChatService;


class ChatController extends AbstractController
{
    /**
     * @Inject
     * @var ChatService
     */
    protected $chatService;

    public function broadcast(RequestInterface $request)
    {
        $message = $request->input('message', 'hello world');
        $server = $this->container->get(ServerFactory::class)->getServer()->getServer();

        $redis = $this->container->get(\Redis::class);
        $fd = $redis->get('WebSocketDemo');
        /**
         * @var  \Swoole\WebSocket\Server $server
         */
        $server->push((int)$fd, $message);
    }


    public function records()
    {
        $authUser = $this->request->getAttribute('authUser');

        $onlineFds = $this->chatService->getConnections();

        $redis = $this->container->get(\Redis::class);
        $onLineUserIds = $redis->hMGet('fdMapUserId', $onlineFds);
        $onLineUserIds = $onLineUserIds ? array_values(array_filter($onLineUserIds)) : [];

        $roomIds = Db::table('user_chat_room')->where(['user_id' => $authUser->id])
            ->pluck('chat_room_id')->toArray();

        $groupRecords = GroupRecord::query()->selectRaw('id,chat_room_id,user_id AS userId,raw_data AS message,created_at')
            ->whereIn('chat_room_id', $roomIds)->get()->groupBy('chat_room_id')->toArray();
        $secretRecords = SecretRecord::query()->where('sender_user_id', $authUser->id)->orWhere('accept_user_id', $authUser->id)
            ->selectRaw('id,sender_user_id AS userId,accept_user_id,raw_data AS message,created_at')
            ->get()->groupBy(function ($item) use ($authUser) {
                return $item['userId'] == $authUser->id ?
                    $item['accept_user_id'] :
                    $item['userId'];
            })->toArray();

        $usersCollects = User::query()->get();
        $userList = [];
        foreach ($usersCollects as $item) {
            if ($item->id != $authUser->id) {
                $userList[] = [
                    'id' => $item->id,
                    'username' => $item->username,
                    'avatar_url' => $item->avatar[0]['url'] ?? '',
                    'online_status' => in_array($item->id, $onLineUserIds) ? 'online' : 'offline'
                ];
            }
        }

        $roomList = ChatRoom::query()->get()->toArray();

        return $this->response->json(['data' => compact(
            'groupRecords',//['roomId1'=>[['userId'=>1,'message'=>'m'],['userId'=>1,'message'=>'m']]]
            'secretRecords', ////['otherUserId1'=>[['userId'=>1,'message'=>'m'],['userId'=>1,'message'=>'m']]],
            'userList',
            'roomList'
        )]);
    }
}
